package com.ztools.pc.service.impl.card;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztools.common.model.pc.card.CardMaster;
import com.ztools.common.model.pc.card.CardRechargeRecord;
import com.ztools.common.model.pc.export.CardRechargeRecordExport;
import com.ztools.common.util.common.PageUtil;
import com.ztools.common.util.common.enumUnit.RechargeTypeEnum;
import com.ztools.pc.mapper.card.CardRechargeRecordMapper;
import com.ztools.pc.service.card.CardMasterService;
import com.ztools.pc.service.card.CardRechargeRecordService;
import com.ztools.pc.util.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author seeTools
 * @since 2023-06-30
 */
@Transactional
@Service
public class CardRechargeRecordServiceImpl extends ServiceImpl<CardRechargeRecordMapper, CardRechargeRecord> implements CardRechargeRecordService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private ExcelUtil excelUtil;
    @Resource
    private CardMasterService cardMasterService;

    /**
     * 分页查询
     *
     * @param pageUtil 分页数据
     * @return 对象
     */
    @Override
    public Page<CardRechargeRecord> findList(PageUtil<CardRechargeRecord> pageUtil) {
        List<OrderItem> orders = new ArrayList<>();
        LambdaQueryWrapper<CardRechargeRecord> queryWrapper = getQueryWrapper(pageUtil.getParams());
        Page<CardRechargeRecord> pages = new Page<>(pageUtil.getPage(), pageUtil.getSize());
        // 排序数据  StrUtil.toUnderlineCase huTools将驼峰装换为下划线格式
        orders.add(new OrderItem(StrUtil.toUnderlineCase(pageUtil.getSortName()), "asc".equals(pageUtil.getSortOrder())));
        pages.setOrders(orders);
        Page<CardRechargeRecord> page = page(pages, queryWrapper);
        dictionary(page.getRecords());
        return page;
    }

    @Override
    public List<CardRechargeRecord> findByObject(CardRechargeRecord cardRechargeRecord) {
        QueryWrapper<CardRechargeRecord> queryWrapper = new QueryWrapper<>(cardRechargeRecord);
        return list(queryWrapper);
    }

    @Override
    public boolean update(CardRechargeRecord cardRechargeRecord) {
        boolean b = false;
        // 修改前先获取，在删除（乐观锁）
        CardRechargeRecord byId = getById(cardRechargeRecord);
        b = updateById(cardRechargeRecord);
        return b;
    }

    @Override
    public boolean delete(CardRechargeRecord cardRechargeRecord) {
        boolean b = false;
        CardRechargeRecord byId = getById(cardRechargeRecord);
        b = removeById(cardRechargeRecord);
        return b;
    }

    @Override
    public void recharge(CardRechargeRecord cardRechargeRecord) {
        if (cardRechargeRecord.getRechargeAmount() != null && cardRechargeRecord.getRechargeAmount().compareTo(BigDecimal.ZERO) > 0) {
            CardMaster cardMaster = cardMasterService.getById(cardRechargeRecord.getCardId());
            BigDecimal amount = cardMaster.getBalance().add(cardRechargeRecord.getRechargeAmount());
            cardRechargeRecord.setRechargeDate(new Date());
            cardRechargeRecord.setBalanceBefore(cardMaster.getBalance());
            cardRechargeRecord.setBalanceAfter(amount);
            cardRechargeRecord.setMemberId(cardMaster.getMemberId());
            save(cardRechargeRecord);
            cardMaster.setBalance(amount);
            cardMasterService.update(cardMaster);
        }
    }

    public LambdaQueryWrapper<CardRechargeRecord> getQueryWrapper(CardRechargeRecord cardRechargeRecord) {
        LambdaQueryWrapper<CardRechargeRecord> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(cardRechargeRecord.getCardNo())) {
            queryWrapper.eq(CardRechargeRecord::getCardNo, cardRechargeRecord.getCardNo());
        }
        if (cardRechargeRecord.getMemberId() != null) {
            queryWrapper.eq(CardRechargeRecord::getMemberId, cardRechargeRecord.getMemberId());
        }
        if (cardRechargeRecord.getRechargeStartDate() != null) {
            queryWrapper.le(CardRechargeRecord::getRechargeDate, cardRechargeRecord.getRechargeStartDate());
        }
        if (cardRechargeRecord.getRechargeEndDate() != null) {
            queryWrapper.le(CardRechargeRecord::getRechargeDate, cardRechargeRecord.getRechargeEndDate());
        }
        return queryWrapper;
    }

    /**
     * 字典翻译
     *
     * @param cardRechargeRecordList 对象集合
     */
    public void dictionary(List<CardRechargeRecord> cardRechargeRecordList) {
        for (CardRechargeRecord cardRechargeRecord : cardRechargeRecordList) {
            dictionary(cardRechargeRecord);
        }
    }

    public void dictionary(CardRechargeRecord cardRechargeRecord) {
        if (cardRechargeRecord != null) {
            if (StrUtil.isNotEmpty(cardRechargeRecord.getRechargeType())) {
                cardRechargeRecord.setRechargeTypeName(RechargeTypeEnum.getEnum(cardRechargeRecord.getRechargeType()).getName());
            }
        }
    }


    @Override
    public void exportExcel(HttpServletResponse response, CardRechargeRecord cardRechargeRecord) {
        long count = count();
        long sheetNumber = ExcelUtil.SHEET_NUMBER;
        long pageSize = excelUtil.getPageSize(sheetNumber, count);
        QueryWrapper<CardRechargeRecord> queryWrapper = new QueryWrapper<>(cardRechargeRecord);
        for (int i = 0; i < pageSize; i++) {
            Page<CardRechargeRecord> pages = new Page<>(i, sheetNumber);
            Page<CardRechargeRecord> page = page(pages, queryWrapper);
            List<CardRechargeRecord> list = page.getRecords();
            dictionary(list);
            excelUtil.exportExcel(response, i, list, CardRechargeRecordExport.class, "基本信息");
        }
    }

    @Override
    public List<CardRechargeRecord> findBy(String fieldName, Object value) {
        QueryWrapper<CardRechargeRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(fieldName, value);
        List<CardRechargeRecord> list = list(queryWrapper);
        dictionary(list);
        return list;
    }

}

